package com.sm.service.serviceImpl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sm.domain.dto.Result;
import com.sm.domain.po.Permission;
import com.sm.mapper.PermissionMapper;
import com.sm.service.PermissionService;
import com.sm.utils.UserHolder;
import com.sun.applet2.preloader.event.ErrorEvent;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
	@Override
	public void bindDefaultRole(Long userId) {
		Permission permission = new Permission();
		permission.setUserId(userId);
		permission.setRoleId(3L);
		save(permission);
		throw new NullPointerException("测试异常");
	}

	@Override
	public Permission getUserRoleCode(Long userId) {
		if(userId == null) {
			return null;
		}

		return lambdaQuery().eq(Permission::getUserId, userId).one();
	}

	@Override
	public Result upgradeToAdmin(Long userId) {
		// 获取当前用户
		Long currentUserId = UserHolder.getUserId();
		// 获取当前用户身份
		Long currentUserRoleId = lambdaQuery().eq(Permission::getUserId, currentUserId).one().getRoleId();

		if(currentUserRoleId != 1L) {
			return Result.error("权限不足");
		}

		boolean success = lambdaUpdate()
				.eq(Permission::getUserId, userId)
				.set(Permission::getRoleId, 2L)
				.update();

		return success ? Result.ok() : Result.error("操作失败");
	}

	@Override
	public Result downgradeToUser(Long userId) {
		// 获取当前用户
		Long currentUserId = UserHolder.getUserId();
		// 获取当前用户身份
		Long currentUserRoleId = lambdaQuery().eq(Permission::getUserId, currentUserId).one().getRoleId();

		if(currentUserRoleId != 1L) {
			return Result.error("权限不足");
		}

		boolean success = lambdaUpdate()
				.eq(Permission::getUserId, userId)
				.set(Permission::getRoleId, 3L)
				.update();

		return success ? Result.ok() : Result.error("操作失败");
	}

	@Override
	public List<Long> getUserRoleIds() {
		List<Permission> permissionList = lambdaQuery().eq(Permission::getRoleId, 3L).list();
		return permissionList.stream().map(Permission::getUserId).collect(Collectors.toList());
	}
}